/*
 * @Description:
 * @Author: Chetwyn
 * @Date: 2019-05-20 14:28:38
 * @LastEditors: Chetwyn
 * @LastEditTime: 2019-08-30 16:55:06
 */
import React, { Component } from 'react';
import { View, StatusBar, Platform } from 'react-native';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { get } from 'lodash';
import {
  RNLoginModule,
  RNCloseModule,
  LoadingProgramModule,
} from 'react-native-cgws-support';

import { DialogAlert } from '../component';
import MyAppNavigator from './AppNavigator';
import {
  fetchData,
  setInitialProps,
  setAuthToken,
  setTicket,
  toggleOverlayContainer,
} from '../actions';
import { LoginType, api } from '../constants';

class Router extends Component {
  constructor(props) {
    super(props);
    this.state = {
      ticketReady: false,
    };
    this.retryLoginCount = 2; // 登录重试次数
    this._setInitialProps();
  }

  componentWillMount() {
    this._checkLogin();

    // 设置状态栏透明，因为安卓原生是沉浸式设计，因此无论这里设置透明还是不透明，安卓的导航栏都必须做一个StatusBar.currentHeight的偏移
    Platform.OS === 'android' && StatusBar.setTranslucent(true);
    // 安卓系统不能调用setBarStyle，因为调用这个接口设置为dark-content的话，Bar会变成不透明
  }

  componentWillUnmount() {}

  render() {
    if (!this.state.ticketReady) {
      return null;
    }

    let params = get(this.props.launchOptions, ['params'], '{}');
    if (params) {
      params = JSON.parse(params);
    }

    return (
      <View style={{ flex: 1 }}>
        <MyAppNavigator params={params} />
      </View>
    );
  }

  _setInitialProps = () => {
    const {
      accsys = '',
      sessionId = '',
      accessToken = '',
      deviceId = '',
      isNightMode = false,
      environment = '',
      hrName = '',
      hrId = '',
      appVersion = '',
    } = this.props.launchOptions;

    this.props.setInitialProps({
      accsys,
      sessionId,
      accessToken,
      deviceId,
      isNightMode,
      environment,
      hrName,
      hrId,
      appVersion,
    });
  };

  _checkLogin = () => {
    const {
      accsys = '',
      accessToken = '',
      sessionId = '',
    } = this.props.launchOptions;
    console.log(
      `====> accsys:${accsys} , accessToken:${accessToken} , sessionId:${sessionId}`
    );
    if (!accessToken || !accsys || !sessionId) {
      console.log('===> 未登录');
      this._login(LoginType.APP_ACCOUNT, (sessionId, accessToken) => {
        this._getTicket(accsys, sessionId, accessToken);
      });
      return;
    }

    this._getTicket(accsys, sessionId, accessToken);
  };

  _login = (loginType, callback) => {
    RNLoginModule.login(loginType, null, result => {
      console.log('====> login result:', result);
      const isAppAccountLogined = get(result, 'isAppAccountLogined', false);
      if (!isAppAccountLogined) {
        RNCloseModule.close();
        return;
      }
      console.log('====>App 账号登录');

      const sessionId = get(result, ['userInfo', 'sessionId'], '');
      const accessToken = get(result, ['userInfo', 'accessToken'], '');
      this.props.setAuthToken({
        sessionId,
        accessToken,
      });

      callback && callback(sessionId, accessToken);
    });
  };

  _getTicket = (accsys, sessionId, accessToken) => {
    const callback = data => {
      console.log('====> getTicket:', data);
      const ticket = get(data, 'ticket', '');
      this.props.setTicket({
        ticket,
      });

      this.setState({
        ticketReady: true,
      });
    };
    const errCallback = error => {
      console.log('====> getTicket error:', error);
      const { code, message } = error;
      if (code === 1 && this.retryLoginCount-- > 0) {
        // 未登录
        this._login(LoginType.APP_ACCOUNT, (sessionId, accessToken) => {
          this._getTicket(accsys, sessionId, accessToken);
        });
      } else {
        LoadingProgramModule.hide();
        this._renderAlert(message);
      }
    };

    this.props.fetchData({
      path: api.ticket,
      method: 'post',
      body: {
        accsys: accsys,
        sessionId: sessionId,
        accessToken: accessToken,
      },
      callback: callback,
      errCallback: errCallback,
      showError: false,
    });
  };

  _renderAlert = messgae => {
    this.props.toggleOverlayContainer({
      visible: true,
      componentCreator: onCloseHandler => {
        return (
          <View
            style={{
              flex: 1,
              justifyContent: 'center',
              alignItems: 'center',
            }}
          >
            <DialogAlert
              title={'打开失败'}
              content={`无法打开小程序，请稍后重试(${messgae})`}
              type={'single'}
              firstBtnTitle={'确认'}
              onFirstBtnPress={() => {
                onCloseHandler && onCloseHandler();
                RNCloseModule.close();
              }}
            />
          </View>
        );
      },
    });
  };
}

const mapStateToProps = state => {
  return {
    isNightMode: state.common.isNightMode,
  };
};

const mapDispatchToProps = dispatch => {
  return bindActionCreators(
    {
      fetchData,
      setTicket,
      setAuthToken,
      setInitialProps,
      toggleOverlayContainer,
    },
    dispatch
  );
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Router);
